package com.kykj.kykj.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kykj.kykj.entity.UserEntity;
import com.kykj.kykj.service.tool.TokenService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component//托管给Spring
public class TokenServiceImpl implements TokenService {
    @Resource
    private  RedisTemplate<String,String> redisTemplate;//注入redis
    /**
     * 生成token
     * @param uname 用户名
     * @return String
     */
    @Override
    public String createToken(String uname) {
        String token = JWT.create().withAudience(uname).sign(Algorithm.HMAC256(uname));
        redisTemplate.opsForValue().set(uname,token,60*6, TimeUnit.MINUTES);//存入redis(有效期是360分钟)
        return token;
    }

    /**
     * 判定Token
     * @param uname 用户名
     * @param token token
     * @return boolean
     */
    @Override
    public boolean isToken(String uname, String token) {
        return redisTemplate.opsForValue().get(uname).equals(token);
    }



    /**
     * 退出登录的时候 删除redis中的key
     * @param uname uname
     * @return boolean
     */
    @Override
    public boolean delToken(String uname) {
        return redisTemplate.delete(uname);
    }

    @Override
    public UserEntity getUserByToken(String token) {
        String result = redisTemplate.opsForValue().get(token);
        if (result == null || result.isEmpty()) {
            return null;
        }

        try {
            return new ObjectMapper().readValue(result, UserEntity.class);
        } catch (Exception e) {
            // 简单打印错误，保持原始逻辑
            System.err.println("Failed to parse user from token: " + e.getMessage());
            return null;
        }
    }

    @Override
    public String createUserToken(String uname, UserEntity userEntity) {
        String token = JWT.create().withAudience(uname).sign(Algorithm.HMAC256(uname));
        try {
            String userJson = new ObjectMapper().writeValueAsString(userEntity);
            redisTemplate.opsForValue().set(token,userJson,60*6, TimeUnit.MINUTES);//存入redis(有效期是360分钟)
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return token;
    }


}
